package com.cosina.game.crystallight.model.crystal;

import android.graphics.Point;
import android.graphics.PointF;

import com.cosina.game.crystallight.MediaPlayerAdapter;
import com.cosina.game.crystallight.engine.BattleEngine;
import com.cosina.game.crystallight.engine.util.Time;
import com.cosina.game.crystallight.model.enemy.Enemy;

public class Tower extends CrystalContainer implements Comparable<Tower>, Time {

	public final Point location;
	public final Point center;

	public Tower(int x, int y) {
		this(new Point(x, y));
	}

	@Override
	public void withTimeGo() {
		if(crystal == null){
			return ;
		}
		crystal.withTimeGo();
		if(crystal.weapon.canAttack()){
			for(Enemy enemy : BattleEngine.enemyManager.enemies){
				if(PointF.length(enemy.center.x - center.x, enemy.center.y - center.y) <= crystal.weapon.range){
					crystal.weapon.attack(this,enemy);
					return;
				}
			}
		}
	}
	
	
	public Tower(Point location) {
		this.location = location;
		this.center = new Point(5 + 44 * location.x + 2 + 23, 5 + 44 * location.y
				+ 2 + 23);
	}

	public void detect() {
		CrystalContainer palmContainer = Palm.getContainer();
		if (null == palmContainer) {
			if (isEmpty() == false) {
				Palm.setContainer(this);
			}
		} else {
			if (isEmpty()) {
				MediaPlayerAdapter.dropCrystal();
				this.crystal = palmContainer.crystal;
				palmContainer.crystal = null;
				Palm.setContainer(null);
			} else if(palmContainer == this){
				Palm.setContainer(null);
			}else{
				Crystal temp = palmContainer.crystal;
				palmContainer.crystal = this.crystal;
				this.crystal = temp;
				Palm.setContainer(null);
			}
		}
	}

	@Override
	public int compareTo(Tower another) {
		if (this.location.y < another.location.y) {
			return -1;
		}
		return 1;
	}


}
